package com.yakaten.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class TestLogin {

	public static void main(String[] args) {
		try {
			
			String surl = "http://localhost:8080/yakaten/login/login";
			
			URL loginUrl = new URL(surl);

			HttpURLConnection connection = (HttpURLConnection) loginUrl
					.openConnection();

			connection.setDoOutput(true);

			OutputStreamWriter out = new OutputStreamWriter(connection
					.getOutputStream(), "UTF-8");

			out.write("userName=admin&password=admin");

			out.flush();
			out.close();

			String cookieVal = connection.getHeaderField("Set-Cookie");

			String s = "http://localhost:8080/yakaten/kakakuPrice";

			URL targetUrl = new URL(s);
			
			HttpURLConnection resumeConnection = (HttpURLConnection) targetUrl
					.openConnection();
			
			if (cookieVal != null) {
				resumeConnection.setRequestProperty("Cookie", cookieVal);
			}
			
			resumeConnection.connect();
			InputStream urlStream = resumeConnection.getInputStream();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(urlStream));
			String ss = null;
			String total = "";
			while ((ss = bufferedReader.readLine()) != null) {
				total += ss;
			}
			IOUtils.write(total, new FileOutputStream("c:/index.html"));
			bufferedReader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
